package com.jack.zk.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class zktest1 {
    private static String connectString = "node1:2181,node2:2181,node3:2183";
    private static int sessionTimeout = 5000;
    private ZooKeeper zkClient = null;


    @Before
    public void init() throws Exception {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
//                List<String> children = null;  //监听节点
//                try {
//                    children = zkClient.getChildren("/jacktest", true);
//                } catch (KeeperException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                for (String child : children) {
//                    System.out.println(child);
//                }
//                System.out.println("=======");
            }
        });
    }
    @Test
    public void ceateNode() throws InterruptedException, KeeperException {
        //ZooDefs.Ids.OPEN_ACL_UNSAFE 为权限控制
        String rs = zkClient.create("/jacktest/test2", "zhao".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println(rs);
    }

    @Test
    public void getChildren() throws Exception {
        List<String> children = zkClient.getChildren("/jacktest", true);  //监听节点
        for (String child : children) {
            System.out.println(child);
        }
// 延时阻塞
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void exist() throws KeeperException, InterruptedException {

        Stat stat = zkClient.exists("/jacktest", false);

        System.out.println(stat==null? "not exist " : "exist");
    }


}
